// pages/refund/refund.js
const app = getApp();
var config = require('../../config');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pics: [],
    pic: [],
    host: config.service.uploadUrl,
    count: 0,
    refundList: true,
    radioValue: '',
    textareaValue: '',
    order_id: '',
    status: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    if (options.status == '0' || options.status == 1){
      wx.request({
        url: app.globalData.host + '/order/refunDetail',
        data: {
          'order_id': options.orderId,
          'session_key': app.globalData.userInfo.sessionKey
        },
        method: "POST",
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        success: function (res) {
          let data = res.data
          if (data.code == 2000) {
            var pic_1 = data.data.pic_1
            var pic_2 = data.data.pic_2
            var pic_3 = data.data.pic_3
            var picture = {pic_1, pic_2, pic_3};
            that.setData({
              radioValue: data.data.remark,
              textareaValue: data.data.detail,
              pics: picture
            })
          } else {
            wx.showToast({ title: data.msg, icon: 'none', duration: 2000 })
          }
        }
      })
    }

    this.setData({
      order_id: options.orderId,
      status: options.status
    })
  },
  clearUl: function () {
    if (this.data.status == '0' || this.data.status == 1){
      return false
    }
    this.setData({
      refundList: !this.data.refundList
    })
  },
  chooseReason: function(e) {
    var that = this;
    var radioValue = e.detail.value;
    app.globalData.radioValue = radioValue;
  },
  choose: function(e) {
  },
  insureReason:function() {
    this.setData({
      radioValue: app.globalData.radioValue
    })
  },
  bindTextAreaBlur:function(e) {
    this.setData({
      textareaValue: e.detail.value
    })
  },
  delPic: function(e) {
    var id = e.currentTarget.dataset.id;
    var pics = this.data.pics;
    for (var i = 0; i < pics.length; i++ ){
      if(i == id){
        this.data.pics.splice(i, 1)
      }
    }
    this.setData({
      pics: this.data.pics,
      count: this.data.pics.length
    })
  },
  uploadPics: function() {
    var host = app.globalData.host;
    var that = this;
    wx.chooseImage({
      count: 3,
      sourceType: ['album', 'camera'],
      success: function (res) {
        var tempFilePaths = res.tempFilePaths
        if ((that.data.pics.length + tempFilePaths.length) > 3){
          wx.showToast({ title: '最多上传3张图片', icon: 'none', duration: 2000 });
          return false;
        }

        for (var i = 0; i < tempFilePaths.length; i++) {
          that.data.pics.push(tempFilePaths[i]);
        }
        that.setData({
          pics: that.data.pics,
          count: that.data.pics.length
        })
      }
    })
  },

  tiJiao: function () {
    var textareaValue = this.data.textareaValue;
    var radioValue = this.data.radioValue;
    var host = app.globalData.host;
    var pics = this.data.pics;
    var that = this;
    var data = {};
    if (radioValue == ""){
      wx.showToast({ title: '请选择退款原因', icon: 'none', duration: 2000 });
      return false;
    }
    data.url = host + '/order/uploadData';
    data.path = pics;

    if(data.path.length ==0 ){
      wx.request({
        url: host + '/order/refund',
        data: {
          'session_key': app.globalData.userInfo.sessionKey,
          'id': that.data.order_id,
          'remark': radioValue,
          'detail': textareaValue,
        },
        method: "POST",
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        success: function (res) {
          let data = res.data
          if (data.code == 2000) {
            wx.redirectTo({
              url: '../order-detail/order-detail?orderId=' + that.data.order_id
            })
          } else {
            wx.showToast({ title: data.msg, icon: 'none', duration: 2000 })
          }
        }
      })
    }else{
      this.uploadImg(data);
    }
  },

  uploadImg: function (data) {
    var radioValue = this.data.radioValue;
    var textareaValue = this.data.textareaValue;
    var pic = [];
    var that = this,
    i = data.i ? data.i : 0, //当前上传的哪张图片
    success = data.success ? data.success : 0, //上传成功的个数
    fail = data.fail ? data.fail : 0; //上传失败的个数
    wx.uploadFile({
      url: data.url,
      filePath: data.path[i],
      name: 'file', //这里根据自己的实际情况改
      success: (res) => {
        success++; //图片上传成功，图片上传成功的变量+1
      },
      fail: (res) => {
        fail++; //图片上传失败，图片上传失败的变量+1
      },
      complete: (res) => {
        var jsonStr = res.data;
        jsonStr = jsonStr.replace(" ", "");
        if (typeof jsonStr != 'object') {
          jsonStr = jsonStr.replace(/\ufeff/g, ""); //重点
          var jj = JSON.parse(jsonStr);
          res.data = jj;
        }
        that.data.pic.push(res.data.file_name);
        i++; //这个图片执行完上传后，开始上传下一张
        if (i == data.path.length) { //当图片传完时，停止调用   
          wx.request({
            url: app.globalData.host + '/order/refund',
            data: {
              'session_key': app.globalData.userInfo.sessionKey,
              'id': that.data.order_id,
              'remark': radioValue,
              'detail': textareaValue,
              'pic_1': that.data.pic[0] ? that.data.pic[0] : "",
              'pic_2': that.data.pic[1] ? that.data.pic[1] : "",
              'pic_3': that.data.pic[2] ? that.data.pic[2] : ""
            },
            method: "POST",
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            success: function (res) {
              let data = res.data
              if (data.code == 2000) {
                wx.redirectTo({
                  url: '../order-detail/order-detail?orderId=' + that.data.order_id
                })
              } else {
                wx.showToast({ title: data.msg, icon: 'none', duration: 2000 })
              }
            }
          })
        } else { //若图片还没有传完，则继续调用函数
          wx.showToast({
            title: "提交中",
            icon: 'loading',
            duration: 1000
          })
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadImg(data);
        }

      }
    });
  },
})